<template>
  <div class="vtk-viewer">
    <div class="file-list-container">
      <h3>VTK 文件列表</h3>
      <ul class="file-list">
        <li
          v-for="file in vtkFiles"
          :key="file"
          @click="loadVtkFile(file)"
          :class="{ active: activeFile === file }"
        >
          {{ file }}
        </li>
      </ul>
    </div>
    <div class="vtk-viewer-container">
      <div ref="vtkContainer" class="vtk-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as vtk from '@kitware/vtk.js';
import { Translate } from '@kitware/vtk.js/Rendering/Core/Transform';
import { PolyDataMapper } from '@kitware/vtk.js/Rendering/Core/PolyDataMapper';
import { Actor } from '@kitware/vtk.js/Rendering/Core/Actor';
import { Camera } from '@kitware/vtk.js/Rendering/Core/Camera';
import { RenderWindow } from '@kitware/vtk.js/Rendering/Core/RenderWindow';
import { RenderWindowInteractor } from '@kitware/vtk.js/Rendering/Core/RenderWindowInteractor';
import { Renderer } from '@kitware/vtk.js/Rendering/Core/Renderer';
import { HttpDataSetReader } from '@kitware/vtk.js/IO/Core/HttpDataSetReader';
import { PolyData } from '@kitware/vtk.js/Common/DataModel/PolyData';

const vtkContainer = ref(null);
const vtkFiles = ref([]);
const activeFile = ref(null);
const renderWindow = ref(null);

const props = defineProps({
  serverUrl: {
    type: String,
    default: 'http://localhost:5000',
    required: true
  }
});

async function fetchVtkFiles() {
  try {
    const response = await fetch(`${props.serverUrl}/api/vtk-files`);
    if (!response.ok) {
      throw new Error('Failed to fetch VTK files');
    }
    const files = await response.json();
    vtkFiles.value = files;
  } catch (error) {
    console.error('Error fetching VTK files:', error);
  }
}

async function loadVtkFile(filename) {
  activeFile.value = filename;
  
  try {
    const reader = HttpDataSetReader.newInstance();
    reader.setURL(`${props.serverUrl}/api/vtk-file/content/${filename}`);
    
    // Wait for the data to load
    await reader.loadData();
    
    // Get the poly data from the reader
    const polyData = reader.getOutputData(0) as PolyData;
    
    // Setup rendering pipeline
    const mapper = PolyDataMapper.newInstance();
    mapper.setInputData(polyData);
    
    const actor = Actor.newInstance();
    actor.setMapper(mapper);
    
    // If renderer isn't initialized yet, create it
    if (!renderWindow.value) {
      const renderer = Renderer.newInstance();
      renderWindow.value = RenderWindow.newInstance();
      
      // Create the interactor
      const interactor = RenderWindowInteractor.newInstance();
      interactor.setRenderWindow(renderWindow.value);
      
      // Connect the render window to the container
      renderWindow.value.addView(renderer);
      interactor.initialize();
      interactor.createInteractor();
      
      // Start the interactor
      interactor.start();
      
      // Set the container size
      const container = vtkContainer.value;
      container.style.width = '100%';
      container.style.height = '100%';
      
      const size = [container.clientWidth, container.clientHeight];
      renderWindow.value.setSize(size);
      
      // Set up resize handling
      window.addEventListener('resize', () => {
        if (!renderWindow.value) return;
        renderWindow.value.setSize([container.clientWidth, container.clientHeight]);
      });
    }
    
    // Clear the renderer
    const renderers = renderWindow.value.getRenderers();
    renderers.forEach(renderer => {
      renderer.removeAllViewProps();
    });
    
    // Add the actor to the renderer
    renderers[0].addActor(actor);
    renderers[0].resetCamera();
    
    // Render
    renderWindow.value.render();
  } catch (error) {
    console.error('Error loading VTK file:', error);
  }
}

onMounted(async () => {
  await fetchVtkFiles();
});
</script>

<style scoped>
.vtk-viewer {
  display: flex;
  height: 100vh;
}

.file-list-container {
  width: 250px;
  background-color: #f5f5f5;
  padding: 10px;
  overflow-y: auto;
  border-right: 1px solid #ddd;
}

.file-list h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
}

.file-list {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.file-list li {
  padding: 8px 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s;
}

.file-list li:hover {
  background-color: #e0e0e0;
}

.file-list li.active {
  background-color: #42b983;
  color: white;
}

.vtk-viewer-container {
  flex: 1;
  position: relative;
}

.vtk-container {
  width: 100%;
  height: 100%;
}
</style>